<template>
  <div>
    <div>
      <el-input style="width: 200px;margin:0 15px" placeholder="查询名称" v-model="name"></el-input>
      <el-button type="primary" @click="load(1)" plain>查询</el-button>
      <el-button type="primary" @click="reset" plain>重置</el-button>
    </div>
    <div style="margin: 10px 0">
      <el-button type="primary" plain @click="handleAdd" v-if="user.role==='管理员'">新增</el-button>
      <el-button type="danger" plain @click="doubleDelete" v-if="user.role==='管理员'">批量删除</el-button>
    </div>
    <el-table :data="tableData" stripe :header-cell-style="{backgroundColor:'aliceblue',color:'#666'}"
              style="margin-top: 20px"
              @selection-change="handleSelectChange">
      <el-table-column type="selection" width="55" align="center" v-if="user.role==='管理员'">
      </el-table-column>
      <el-table-column prop="id" label="序号" width="70" align="center"></el-table-column>
      <el-table-column prop="name" label="商品名称"></el-table-column>
      <el-table-column prop="goodsContent" label="商品描述"></el-table-column>
      <el-table-column prop="price" label="商品价格" :formatter="formatPrice"></el-table-column>
      <el-table-column label="操作" align="center" style="margin-left: 10px">
        <template v-slot="scope" >
          <el-input
              @input="handleInputChange($event, scope.$index)"
              v-model="buyNumber[scope.$index]"
              type="number"
              min="1"
              placeholder="购买数量"
              size="small"
              style="width: 100px;margin-right: 10px"

              >
<!--v-if="user.role === '用户'"-->
          </el-input>
          <el-button type="primary" size="small" @click="buy(scope.row, scope.$index)" >购买</el-button><!--v-if="user.role === '用户'"-->
          <el-button size="small" type="primary" @click="handleEdit(scope.row)" v-if="user.role==='管理员'">编辑</el-button>
          <el-button size="small" type="danger" @click="del(scope.row.id)" v-if="user.role==='管理员'">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin:10px 0">
      <el-pagination
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-size="pageSize"
          layout="total,prev, pager, next"
          :total="total">
      </el-pagination>
    </div>
    <el-dialog title="商品信息" :visible.sync="formVisible" width="30%" v-if="user.role === '管理员'">
      <el-form :model="form" label-width="80px" style="padding-right: 50px"  ref="formRef">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="商品描述" prop="goodsContent">
          <el-input type="textarea" v-model="form.goodsContent"></el-input>
        </el-form-item>
        <el-form-item label="商品价格" prop="goodsPrice">
          <el-input v-model="form.price"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="formVisible = false">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="选择设备" :visible.sync="equipmentVisible" width="30%">
      <el-form :model="form" label-width="80px" style="padding-right: 50px"  ref="formRefEquipment">
        <el-form-item label="选择设备" prop="equ">
          <el-select v-model="selectedEquipment" @change="updateEquipment" placeholder="请选择设备">
            <el-option
                v-for="item in equimentOption"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="equipmentVisible = false">取消</el-button>
        <el-button type="primary" @click="buyGoods">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request";
import axios from "axios";

export default {
  name: "Goods",
  data() {
    return {
      user: JSON.parse(localStorage.getItem('base-user') || '{}'),
      tableData: [],//所有数据
      pageNum: 1,//当前页码
      pageSize: 6,//每页显示个数
      name: '',
      total: 0,
      formVisible: false,
      equipmentVisible:false,
      form: {},
      buyNumber:{},
      equimentOption:'',
      selectedEquipment:'',
      buyGoodsName:'',
      num:0,
      totalPrice:0,
      count:0,
    }
  },
  created() {
    this.load()
    this.fetchEquipment()
  },
  methods: {
    handleInputChange(value, index) {
      const numValue = Number(value)
      if (Number.isInteger(numValue)) {
        this.$set(this.buyNumber, index, numValue)
      } else {
        const intValue = Math.floor(numValue)
        this.$set(this.buyNumber, index, intValue)
        this.$message.warning('购买数量必须为整数！')
      }
    },
      updateEquipment() {
      const selectedItem = this.equimentOption.find(item => item.value === this.selectedEquipment)
      this.form.equ = selectedItem.label
      this.selectedEquipment = selectedItem.label
    },
    fetchEquipment() {
      this.$request.get('/equipment/selectAll').then(response => {
        this.equimentOption = response.data.map(item => ({
          value: item.id,
          label: item.name,
        }))
      })
    },
    formatPrice(row, column, cellValue, index) {
      return cellValue + '元';
    },
    buy(row,index) {
      this.equipmentVisible = true;
      this.buyGoodsName = row.name;
      // 假设 buyNumber 是以索引为键的对象，获取对应的购买数量
      const number = this.buyNumber[index] || 1;
      this.num = number;
      this.totalPrice = row.price * number;
      this.count = 2 * number;
    },
    buyGoods(){
      const data = {
        equName: this.selectedEquipment,
        useCount: this.count,
        goodsName: this.buyGoodsName,
        num: this.num,
        total: this.totalPrice,
        useId:this.user.id,
      };
      this.$request.put('/equipment/update2', {
        name: this.selectedEquipment,
        count: this.count,
      }).then(updateRes => {
        if (updateRes.code === '200' && updateRes.waterSufficient) {
          request.post('/orders/add', data).then(res => {
            this.$message.success('下单成功！请支付')
            this.equipmentVisible = false
          })
        } else {
          this.$message.error('该设备剩余水量不足');
        }
      }).catch(error => {
        this.$message.error('更新设备剩余水量时出错');
      });
    },
    doubleDelete() {
      if (!this.ids.length) {
        this.$message.warning("请选择商品")
        return
      }
      this.$confirm("确认批量删除这些商品么", "确认删除", {type: "warning"}).then(response => {
        this.$request.delete('/goods/delete/double', {data: this.ids}).then(res => {
          if (res.code === "200") {//操作成功
            this.$message.success("操作成功")
            this.load(1)
          } else {
            this.$message.error(res.msg)
          }
        })
      }).catch(() => {
      })
    },
    handleSelectChange(rows) {
      this.ids = rows.map(v => v.id)
    },
    del(id) {
      this.$confirm("确认删除么", "确认删除", {type: "warning"}).then(response => {
        this.$request.delete('/goods/delete/' + id).then(res => {
          if (res.code === "200") {//操作成功
            this.$message.success("操作成功")
            this.load(1)
          } else {
            this.$message.error(res.msg)
          }
        })
      }).catch(() => {
      })
    },
    handleEdit(row) {//编辑数据
      this.form = JSON.parse(JSON.stringify(row)) //给form对象赋值，注意要深拷贝数据
      this.formVisible = true
    },
    handleAdd() {//新增数据
      this.form = {}//点击新增数据的时候首先清空表
      this.formVisible = true//打开弹窗
    },
    save() { //保存按钮触发逻辑，触发新增或更新
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.$request({
            url: this.form.id ? '/goods/update' : '/goods/add',
            method: this.form.id ? 'PUT' : 'POST',
            data: this.form
          }).then(res => {
            if (res.code === '200') {
              this.$message.success('保存成功')
              this.load(1)
              this.formVisible = false
            } else {
              this.$message.error(res.msg)//输出错误信息
            }
          })
        }
      })
    },
    reset() {
      this.name = ''
      this.load()
    },
    handleCurrentChange(pageNum) {
      this.load(pageNum)
    },
    load(pageNum) {  //分页查询
      if (pageNum) this.pageNum = pageNum
      this.$request.get('/goods/selectByPage', {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          name: this.name,
        }
      }).then(res => {
        // 检查 res.data 是否为 null 或 undefined
        if (res.data === null || res.data === undefined) {
          // 处理错误情况，例如显示错误消息或清空表格数据
          console.error('未获取到数据');
          this.tableData = [];
          this.total = 0;
        } else {
          // 正常处理数据
          this.tableData = res.data.records;
          this.total = res.data.total;
        }
      }).catch(error => {
        // 处理请求错误
        console.error('请求数据出错:', error);
        // 可以根据需要设置一些错误处理逻辑，比如显示错误消息
      });
    },
  }
}
</script>

<style scoped>

</style>